package com.wxzz.elearning.common.utils;

import java.math.BigDecimal;

import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * 获取全局默认配置工具类
 */
public class ServerConfigConmonUtil {
    public static final String SERVER_CONFIG_KEY = "gushen_server_config";
    public static final String SERVER_CONFIG_KEY_PX = ":";

    /**
     * 获取全局默认配置的值
     * @param key
     * @param redisTemplate
     * @return 不存在时返回null
     */
    public static String get(String key, RedisTemplate redisTemplate){
        HashOperations hashOperations = redisTemplate.opsForHash();
        Object object = hashOperations.get(SERVER_CONFIG_KEY, key);
        return object!=null? (String) object :null;
    }


    /**
     * 优先获取租户自定义值   如何租户没有自定义值，则返回全局的值。
     * @param key
     * @param tenantId
     * @param redisTemplate
     * @return 不存在时返回null
     */
    public static String get(String key,Long tenantId, RedisTemplate redisTemplate){
        HashOperations hashOperations = redisTemplate.opsForHash();
        Object objectTenant = hashOperations.get(SERVER_CONFIG_KEY, key+SERVER_CONFIG_KEY_PX+tenantId);
        if (objectTenant!=null){
            return (String) objectTenant;
        }else {
            return get(key,redisTemplate);
        }
    }

    public static <T> T get(String key,Long tenantId, RedisTemplate redisTemplate,T defValue) {
        String strVal = get(key,tenantId, redisTemplate);
        if(strVal==null) {
            return defValue;
        }else if(defValue instanceof Boolean) {
            return (T)Boolean.valueOf(strVal);
        }else if(defValue instanceof Long) {
            return (T)Long.valueOf(strVal);
        }else if(defValue instanceof Integer) {
            return (T)Integer.valueOf(strVal);
        }else if(defValue instanceof BigDecimal) {
            return (T) new BigDecimal(strVal);
        }
        return (T)strVal;
    }

}
